<template>
  <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
    <el-form-item label="密码" prop="password">
      <el-input type="password" v-model="form.password" @input="validatePassword" placeholder="Enter your password"></el-input>
      <span v-if="passwordError" class="error-message">{{ passwordError }}</span>
    </el-form-item>
    <el-form-item label="确认密码" prop="repassword">
      <el-input type="password" v-model="form.repassword" @input="validateRepassword" placeholder="Confirm your password"></el-input>
      <span v-if="repasswordError" class="error-message">{{ repasswordError }}</span>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<style>
.error-message {
  color: red;
  font-size: 12px;
}
</style>
<script setup>
import { reactive, ref } from 'vue';
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';

// 定义表单模型
const form = reactive({
  password: '',
  repassword: ''
});

// 定义错误消息
const passwordError = ref('');
const repasswordError = ref('');

// 定义表单验证规则
const rules = {
  password: [
    { required: true, trigger: 'blur', message: '密码不能为空' },
    { min: 6, max: 20, trigger: 'blur', message: '密码长度在6-20位' }
  ],
  repassword: [
    { required: true, trigger: 'blur', message: '请确认密码' },
    { validator: validateRepassword, trigger: 'blur' }
  ]
};

// 定义表单引用
const formRef = ref(null);

// 验证密码
const validatePassword = () => {
  if (form.password.length < 6 || form.password.length > 20) {
    passwordError.value = '密码长度在6-20位';
  } else {
    passwordError.value = '';
  }
  validateRepassword();
};

// 验证确认密码
const validateRepassword = () => {
  if (form.repassword === '') {
    repasswordError.value = '请确认密码';
  } else if (form.repassword !== form.password) {
    repasswordError.value = '两次输入密码不一致';
  } else {
    repasswordError.value = '';
  }
};

// 提交表单
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('提交成功');
    } else {
      ElMessage.error('提交失败');
      return false;
    }
  });
};
</script>

